package com.qqonline.conmon;

import org.json.JSONException;
import org.json.JSONObject;

import com.qqonline.conmon.async.AsyncGet;
import com.qqonline.conmon.async.AsyncGetImage;
import com.qqonline.conmon.async.AsyncTaskPost;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.TextView;

public class QRCodeUtil {

	private static final String ACCESSTOKENURL=DATA.ACCESSTOKENURL;
	private static final String TICKETURL=DATA.TICKETURL;
	private static final String QRCODEIMAGEURL=DATA.QRCODEIMAGEURL;
	private AsyncGet get;
	private AsyncTaskPost post;
	private AsyncGetImage getImage;
	private ImageView iv;
	private TextView tv;
	private Bitmap bitmap;
	private IDoPostBack iLoaded;
	public QRCodeUtil(Activity context,final int scene_id ,IDoPostBack iLoaded) {
		iv=null;
		tv= null;
		this.iLoaded=iLoaded;
		get=new AsyncGet(context, new AsyncGet.MyDoPostBack() {			
			@Override
			public void DoPostBack(String json) {
				setText("access_token:"+json);
				String params="{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+scene_id+"}}}";
				post.setJsonParams(params);
				post.execute(TICKETURL+json);
			}
		});
		post=new AsyncTaskPost(new AsyncTaskPost.DoPostBack() {
			
			@Override
			public void PostBack(String result) {
				setText("ticket:"+result);
				JSONObject json;
				try {
					json = new JSONObject(result);
					String ticket=json.getString("ticket");
					getImage.execute(QRCODEIMAGEURL+ticket);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
		});
		getImage=new AsyncGetImage(new AsyncGetImage.MyDoPostBack() {
			
			@Override
			public void DoPostBack(byte[] bytes) {
				if(bytes ==null)
				{
					return;
				}
				bitmap=BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
				setImage(bitmap);
				if(QRCodeUtil.this.iLoaded != null)
				{
					QRCodeUtil.this.iLoaded.BitmapLoaded(bitmap);
				}
			}
		});
		
	}
	private void setText(String text)
	{
		if(tv != null)
		{
			tv.setText(text);
		}
	}
	private void setImage(Bitmap bitmap)
	{
		if(iv != null)
		{
			iv.setImageBitmap(bitmap);
		}
	}
	public void setImageView(ImageView iv) {
		this.iv=iv;
	}
	public void setTextView(TextView tv)
	{
		this.tv=tv;
	}
	public void asyncGetBitmap()
	{
		get.execute(ACCESSTOKENURL);
	}
	public interface IDoPostBack
	{
		public void BitmapLoaded(Bitmap bitmap) ;
	}
}
